const Router = require('koa-router');
const router = new Router();
router.prefix('/acl'); //路由前缀
const Joi = require('joi'); //前端参数验证
const moment = require('moment'); //时间格式化
const token = require('../utility/token'); //token公共方法
const common = require('../utility/common'); //程序公共方法
const verifyWeb = require("../config/verifyWeb"); //验证前端参数
const mongoose = require('mongoose'); //导入mongoose
// acl权限控制
// const nodeAcl = require('acl');
// const acl = new nodeAcl.mongodbBackend(mongoose.connection.db, 'acl_');

//模型
const UserModel = require("../models/user"); //用户

//数据库字段
const dbDoc = require("../config/dbDoc");

//用户登录
router.post('/login', async (ctx) => {
    //定义返回值
    let cb = {
        sta: false,
        msg: '登陆失败',
        region: '',
        code: '',
        token: ''
    };
    try {
        //前端参数
        let req = ctx.request.body;
        //验证用户名是否存在
        let verifyName = await UserModel.findOne({
            name: String(req.name)
        });
        if (!verifyName) {
            cb.msg = '用户名未注册';
            return ctx.body = cb;
        }
        //验证用户名、密码是否匹配
        let verifyPwd = await UserModel.findOne({
            'name': String(req.name),
            'password': String(req.password)
        });
        if (!verifyPwd) {
            cb.msg = '密码错误';
            return ctx.body = cb;
        }
        //生成jwt
        let paramToken = {
            exp: Math.floor(Date.now() / 1000) + (60 * 600),
            id: verifyPwd._id
        };
        let tokenSign = await token.sign(paramToken); //签名
        if (!tokenSign) {
            cb.msg = 'token生成失败';
            return ctx.body = cb;
        }
        //构造返回值
        cb.sta = true;
        cb.msg = '验证成功';
        cb.region = verifyPwd.region;
        cb.code = verifyPwd.region;
		cb.token = tokenSign;
    } catch (e) {
        cb = {
            msg: '登陆失败',
        };
    } finally {
        ctx.body = cb;
    }
});

//用户列表
router.post('/userList', async (ctx) => {
    //定义返回值
    let cb = [];
    try {
        //根据用户权限获取用户权限
        let userRegion = await common.region(ctx, 6);
        let userList = await UserModel.find({
            region: userRegion 
        });
        if(userList.length){
            let callback = userList.map(obj => {
                let newObj = {};
                //构造id
                newObj.id = obj._id;
                //用户名
                newObj.name = obj.name;
                //权限
                newObj.region = obj.region;
                //解析时间
                newObj.crtime = moment(obj.crtime).format('YYYY-MM-DD HH:mm:ss');
                newObj.chtime = moment(obj.chtime).format('YYYY-MM-DD HH:mm:ss');
                return newObj;
            });
            cb = callback;
        }
    } catch (e) {
        cb = [];
    } finally {
        ctx.body = cb;
    }
});

//用户新增
router.post('/userAdd', async (ctx) => {
    //定义返回值
    let cb = {
        sta: false,
        msg: '新增用户失败'
    };
    try {
        //前端参数
        let req = ctx.request.body;
        //前端参数验证
        let valityWeb = await Joi.validate({
            name: req.name,
            password: req.password,
            region: req.region
        }, verifyWeb.userAdd);
        if(!valityWeb){
            cb.msg = '前端参数错误';
            return ctx.body = cb;
        }
        //验证用户名是否存在
        let verifyName = await UserModel.findOne({
            name: String(req.name)
        });
        if (verifyName) {
            cb.msg = '用户名已存在';
            return ctx.body = cb;
        }
        //存储用户
        let user = new UserModel({
            _id: mongoose.Types.ObjectId(),
            name: req.name,
            password: req.password,
            crtime: moment().format('X'),
            chtime: moment().format('X'),
            region: req.region
        });
        let save = await user.save();
        //构造返回值
        cb = {
            sta: true,
            msg: '新增用户成功',
            cb: save
        };
    } catch (e) {
        cb = {
            sta: false,
            msg: '新增用户失败'
        };
    } finally {
        ctx.body = cb;
    }
});

//用户详情
router.post('/userDetail', async (ctx) => {
    //定义返回值
    let cb = {
        list: {},
        sta: false,
        msg: '获取用户详情失败'
    };
    try {
        //前端参数
        let req = ctx.request.body;
        //前端参数验证
        let valityWeb = await Joi.validate({
            _id: req._id
        }, verifyWeb._id);
        if(!valityWeb){
            cb.msg = '前端参数错误';
            return ctx.body = cb;
        }
        //查询用户
        let user = await UserModel.findById(mongoose.Types.ObjectId(req._id), dbDoc.user).lean();
        if (user) {
            for (let i in user) {
                if (i == 'crtime' || i == 'chtime') {
                    user[i] = moment(Date.now(user[i])).format('YYYY-MM-DD HH:mm:ss');
                } else {
                    // user[i] = user[i];
                }
            }
        }
        //构造返回值
        cb.list = user;
        cb.sta = true;
        cb.msg = '获取用户详情成功';
    } catch (e) {
        cb = {
            list: {},
            sta: false,
            msg: '获取用户详情失败'
        };
    } finally {
        ctx.body = cb;
    }
});

//用户编辑
router.post('/userEdit', async (ctx) => {
    //定义返回值
    let cb = {
        sta: false,
        msg: '编辑用户失败'
    };
    try {
        //前端参数
        let req = ctx.request.body;
        console.log('req', req);
        //前端参数验证
        let valityWeb = await Joi.validate({
            _id: req._id,
            name: req.name,
            password: req.password,
            region: req.region
        }, verifyWeb.userEdit);
        console.log('valityWeb', valityWeb);
        if (!valityWeb) {
            cb.msg = '参数错误';
            return ctx.body = cb;
        }
        //验证是否存在
        let verifyExist = await UserModel.findById(mongoose.Types.ObjectId(req._id), dbDoc.user).lean();
        console.log('verifyExist', verifyExist);
        if (!verifyExist) {
            cb.msg = '用户不存在';
            return ctx.body = cb;
        }
        //更新
        let doc = {};
        for (let i in req) {
            if (i != '_id') {
                doc[i] = req[i];
            }
            doc.chtime = moment().format('X');
        }
        let updateOne = await UserModel.findOneAndUpdate(req._id, doc, {
            new: true
        });
        console.log('updateOne', updateOne);
        //构造返回值
        if (updateOne) {
            cb = {
                sta: true,
                msg: '编辑用户成功',
                cb: updateOne
            };
        }
    } catch (e) {
        cb = {
            sta: false,
            msg: '编辑用户失败'
        };
    } finally {
        ctx.body = cb;
    }
})
module.exports = router;